package com.ffmpeg.util.app.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.Optional;

import com.ffmpeg.util.app.FileInfoService;
import com.ffmpeg.util.domain.entity.FileInfo;
import com.ffmpeg.util.infra.constant.FileConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;

/**
 * @author :wm
 * @description :fileInfo实现类
 */
@Service
public class FileInfoServiceImpl implements FileInfoService {

    private final static Logger logger = LoggerFactory.getLogger(FileInfoServiceImpl.class);

    @Override
    public FileInfo queryFileInfoByAbsolutePath(String absolutePath, Boolean additionalInformationFlag) {
        File file = new File(absolutePath);
        if (!file.exists()) {
            logger.error("file not exist");
            return new FileInfo();
        }
        FileInfo fileInfo = new FileInfo();

        //文件名
        fileInfo.setFileName(absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.lastIndexOf('.')));
        //文件类型
        if (file.isDirectory()) {
            fileInfo.setFileType(FileConstant.FileType.DIR);
        } else {
            fileInfo.setFileType(absolutePath.substring(absolutePath.lastIndexOf('.') + 1));
        }
        //文件目录
        fileInfo.setDirPath(absolutePath.substring(0, absolutePath.lastIndexOf("\\")));
        //文件大小
        fileInfo.setSize(new BigDecimal(file.length()));
        //是否获取附加文件信息，若不获取可返回简易信息结果
        additionalInformationFlag = Optional.ofNullable(additionalInformationFlag).orElse(false);
        if (!additionalInformationFlag) {
            return fileInfo;
        }
        //文件时长
        MultimediaObject multimediaObject = new MultimediaObject(file);
        try {
            fileInfo.setTime(multimediaObject.getInfo().getDuration());
        } catch (EncoderException e) {
            logger.error("can't get file time");
            fileInfo.setTime(0L);
        }

        return fileInfo;
    }

    @Override
    public Boolean createRootDir() {
        return null;
    }
}
